package com.salemanagement.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.three.core.entity.ProductOrder;
import com.salemanagement.vo.StoreIncomeVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
* @author liuliyuan
* @description 针对表【tb_order(订单)】的数据库操作Mapper
* @createDate 2025-03-14 10:57:58
* @Entity com.lly.entity.Order
*/
@Mapper
public interface OrderMapper extends BaseMapper<ProductOrder> {

    @Select("SELECT store_name as storeName FROM tb_store ORDER BY store_name")
    List<Map<String, Object>> selectAllStores();

    @Select({
        "<script>",
        "SELECT ",
        "    s.store_name as storeName, ",
        "    COALESCE(SUM(CASE WHEN o.status_code IN (41, 43) AND o.total_amount > 0 THEN o.total_amount ELSE 0 END), 0) as sum ",
        "FROM tb_store s ",
        "LEFT JOIN tb_product_order o ON s.store_name = o.store_name ",
        "<where>",
        "    <if test='date != null and date != \"\"'>",
        "        AND DATE_FORMAT(o.create_time, '%Y-%m') = #{date}",
        "    </if>",
        "    <if test='storeName != null and storeName != \"\"'>",
        "        AND s.store_name = #{storeName}",
        "    </if>",
        "    AND (o.status_code IN (41, 43) OR o.status_code IS NULL)",
        "</where>",
        "GROUP BY s.store_name",
        "HAVING sum > 0",
        "ORDER BY sum DESC",
        "</script>"
    })
    List<StoreIncomeVO> findIncome(@Param("date") String date, @Param("storeName") String storeName);
}
